package base.thread_demo.demo08_02;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 有时候需求要将线程串行化,join方法可以实现线程串行化运行
 */
public class JoinDemo {
    private static final Logger log = LoggerFactory.getLogger(JoinDemo.class);

    public static void main(String[] args) throws InterruptedException {
        Thread t1 = new ThreadJoin("李渊");// 父
        Thread t2 = new ThreadJoin("李世民");// 子
        Thread t3 = new ThreadJoin("李元霸");// 子, 是李世民弟弟

        t1.start();
        t1.join();//t2和t3线程要等待t1线程结束，才可以执行各自的业务,注意这句要在t1线程启动后才能执行.
//        t1.join(5000);//表示t2和t3只等待t1线程5s，5s后就和t1争夺CPU执行权。

        t2.start();
        t3.start();
    }


    static class ThreadJoin extends Thread {
        public ThreadJoin(String name){
            super(name);
        }
        @Override
        public void run() {
            for (int i = 0; i < 100; i++) {
                try {
                    //模拟任务在执行过程中耗时
                    Thread.sleep(100);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                log.info("{}: {}", getName(), i);
            }
        }
    }
}
